import axios from 'axios'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 不需要token的白名单
    const whiteList = ['/user/login', '/user/register']
    
    // 如果不在白名单中，则添加token
    if (!whiteList.includes(config.url)) {
      const token = localStorage.getItem('token')
      if (token) {
        // 添加 Authorization 头
        config.headers.Authorization = token
      }
    }

    // 如果是 POST 或 DELETE 请求，修改 Content-Type
    if (config.method === 'post' || config.method === 'delete') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response && error.response.status === 401) {
      // token 失效，清除用户信息并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default request 